<?php

	include("../config.php");
	include(INCLUDEDIR."core.php");
	
	db::Connect();
	
	$rate = isset($_REQUEST['rate'])?intval($_REQUEST['rate']):0;
	$id_profesor = intval($_REQUEST['idp']);
	$id_persona = intval($_REQUEST['idy']);
	
	$query = " SELECT * FROM rating_profesores WHERE id_persona = '$id_persona' AND id_profesor = '$id_profesor'";
	
	$votacion = db::getRow($query);
	
	if(count($votacion)==0) {
		if($id_profesor>0 && $id_persona>0 && $id_profesor!=$id_persona) {
			$query = "INSERT INTO rating_profesores (id_persona,id_profesor,rate) VALUES ('$id_persona','$id_profesor','$rate')";
			mysql_query($query);
		}
	}
	
	$avg = db::getRow("SELECT CAST(COALESCE(AVG(rate),0) AS DECIMAL(5,2)) AS avg, COUNT(*) AS votes FROM rating_profesores WHERE id_profesor = '$id_profesor'");
	$avg['selected'] = intval(round($avg['avg'])-1);
	
	
	echo(json_encode($avg));
?>